/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlsigingexample;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Element;

/**
 *
 * @author Pawel
 */
public class XMLParser {
    public static Element parseToXmlSimpleObject(Object object){
            Class theClass = object.getClass();
                Element msg = new Element(theClass.getSimpleName());
	        Field[] fields = theClass.getDeclaredFields();
	
	        for (int i = 0; i < fields.length; i++) {
	           // Type type=fields[i].getType();
	            fields[i].setAccessible(true);
	            
                    Element help = new Element(fields[i].getName());
            try {
                help.addContent( fields[i].get(object).toString());
                msg.addContent(help);
                
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(XMLParser.class.getName()).log(Level.SEVERE, null, ex);
            }
                }    
            return msg;
         //  return null;
    }
    
    public static void parseObjectFromXml(Element msg, Object object) throws IllegalArgumentException, IllegalAccessException{
        Class theClass = object.getClass();
	
        Field[] fields = theClass.getDeclaredFields();
	
       for (int i = 0; i < fields.length; i++) {
	      Type type=fields[i].getType();
	      fields[i].setAccessible(true); 
              Element help = msg.getChild(fields[i].getName());
                if (fields[i].getType().equals(String.class)) {
	               fields[i].set(object, help.getValue());
	            }
	            //detect int or Integer
	            if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
	              fields[i].set(object, Integer.getInteger(help.getValue()));
	            }
	            
	            //detect float or Float
	            if (type.equals(Float.TYPE) || type.equals(Float.class)) {
	                 fields[i].set(object, Float.parseFloat(help.getValue()));
	            }
	            
	            if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
                         fields[i].set(object, Boolean.parseBoolean(help.getValue()));
	            }
	        }
              
       
         
        
    }
}
